/**
 * @author Trevor Carothers
 */

$(document).ready(function() {
	/*Check if a the user is logged in, if not redirect to login page
	* If the user is not logged in, alert and then redirect
	*/
	if( !checkLogin() ){
		alert("User is not logged in, click to redirect to login page.");
		window.location ='/index.html';
		return;	//return so no other code initializations are executed
	}
		
	bindButtons();
	
	Account_Settings.Init();
});

var Account_Settings = {

	Init : function() {	
		//Bind all listeners to their corresponding buttons
		this.addAllListeners();
			
		//Hide the change password field at the start
		var el = $(".account-settings-change-password-toggle");
		this.handleHideChanges(el);
		
		//Populate user fields with values in the DB
		this.populateUserInfo();
		
		this.checkAdmin();
	
	},
	checkAdmin : function(){
		 var $this = this;
		 callApi('userApi', 'isAdmin', 'POST',{}, function(resultObj){
		 	if (resultObj.success)
		 		$this.bindAdminOverlay();
			else
				$('.admin-overlay').hide();
		 }, '', '', true);
	},
	bindAdminOverlay : function(){
		//add admin option
		$('.main-header .menu-btn .clear').before('<a class="admin">Add Admin</a>');
		
		//start dialog
		$('.admin-overlay').dialog({
			width : 350,
			show : 'blind',
			draggable: true,
			title: 'Add Administrator',
			autoOpen : false,
			closeText : 'Close',
		});
		this._overlay = $('.admin-overlay');
		
		var $this = this;
		
		var listAdmin = function(){
			callApi('userApi', 'listUsers', 'POST',{}, function(resultObj){
		 	if (resultObj.success){
				$this._users = resultObj.users;
				$.each(resultObj.users, function(key,val){
					if(val.privilege  == '0' && val.email != $this._myEmail )
						$('.ui-dialog .useremail #Select1').append($("<option id="+val.user_id+"></option>").text(val.email));
				});
			}
			else
		 		alert('administrator list cannot be retrived, please try again.');
			}, '', '', true);
		}
			
		//open admin overlay on click
		$('a.admin').click(function(){
			$this._overlay.dialog('open');
			$('#Select1 option').each(function(i, selected){
				$(selected).remove();
			});
			listAdmin();
		});
		
		//add new admin email
		$('.admin-overlay .promote').click(function(){
			var newuseremail = $(".ui-dialog .new-project-overlay-email input").val().replace(/ /g,'');
					
			var newAdmin = true;
			$('.ui-dialog .useremail #Select1 option').each(function(){
				if ($(this).text() == newuseremail) {
					newAdmin = false;
					alert('user is already an admin');
				}
			})
			
			if(newuseremail != '' && newAdmin){
				var getUid = function(resultObj){
	                if (resultObj.success) {
	                    userID = resultObj.userId;
								
						//add user to admin list
						callApi('userApi', 'promoteUser', 'POST', {userId: userID}, function(resultObj){
							if (resultObj.success) 
								$('.ui-dialog .useremail #Select1').append($("<option id="+userID+"></option>").text(newuseremail));
							else
	 							alert(resultObj.message);
						},'', '', false);
	                }
					else	
						alert(resultObj.message);
            	}
				callApi('userApi', 'getUidFromEmail', 'POST', {
                    email: newuseremail
                }, getUid, '', '', false);
			}
       		
		});
		
		//delete email
		$('.admin-overlay .remove').click(function(){
			// Get project name 
			var removeAdmin = function(resultObj){
				 if (resultObj.success) {
	                    userID = resultObj.userId;
						//add user to admin list
						callApi('userApi', 'demoteUser', 'POST', {userId: userID}, function(resultObj){
							if (resultObj.success) 
								$('.ui-dialog .useremail #'+userID).remove();
							else
	 							alert(resultObj.message);
						},'', '', false);
	                }
					else	
						alert(resultObj.message);
			}
            $('#Select1 :selected').each(function(i, selected){
               // $(selected).remove();
				callApi('userApi', 'getUidFromEmail', 'POST', {
                    email: selected.text
                }, removeAdmin, '', '', false);
            });
		});
		
		//close
		$('.admin-overlay .close').click(function(){
            $this._overlay.dialog('close');
		});
	
		  
	},

	checkPassword : function( email, password){
		var t = this;
		var url = 'lib/userApi.php?__m=login&__d=';
		
		var encodedpass = hex_md5(password);
		
		var para = {"email" : email, "password" : encodedpass, "remember" : 0};
		
		//encode the parameters
		var para_encoded = JSON.stringify(para);
		
		url += para_encoded;
		var retval;
		
	    $.ajax({
		  url: url,
		  async:false,
		  success: function( result ) {
		   		var msg = jQuery.parseJSON(result);
		   		retval = msg.success;
		   		if( !retval ){
		   			alert(msg.message);
		   			return;
		   		}	
		  },
		  error: function(){
		  		alert('oops, we got an error!');
		  }
		});

		return retval;
		
	},
	
	populateUserInfo : function(){
		var url = 'lib/userApi.php?__m=getInfo&__d=';
		
		var para = {};
			
		//encode the parameters
		var para_encoded = JSON.stringify(para);
			
		url += para_encoded;
	
		var $this = this;
		//ajax call to get result
		$.ajax({
		  url: url,
		  success: function( result ) {
		   		var msg = jQuery.parseJSON(result);
		   		var success = msg.success;
		   		if( !success ){
		   			alert(msg.message);
		   			return;
		   		}		   		
		   		
		   		var userId = msg.userId;
				var email = msg.email;
				$this._myEmail = email;
		   		var firstName = msg.firstName;
		   		var lastName = msg.lastName;
		   		var projectId = msg.projectId;
		   		

		   				   		
		   		$('.account-settings-body-names-first-body').find(':input').val(firstName);
		   		$('.account-settings-body-names-last-body').find(':input').val(lastName);
		   		$('.account-settings-body-email-body').find(':input').val(email);

		  },
		  error: function(){
		  		alert('oops, we got an error!');
		  }
		});
	},
	
	clearPasswordFields : function(){
		// Remove the old passwords
		  $('.account-settings-body-password-body').find(':input').val("");
		  $('.account-settings-body-changepass-body').find(':input').val("");
		  $('.account-settings-body-changepassconf-body').find(':input').val("");
	},
	
	submitUserAccountChanges : function(){
		var t = this;
		var url = 'lib/userApi.php?__m=editInfo&__d=';
		
		//obtain paramaters
		var first = $('.account-settings-body-names-first-body').find(':input').val();
		var last = $('.account-settings-body-names-last-body').find(':input').val();
		var em = $('.account-settings-body-email-body').find(':input').val();
		var currpass = $('.account-settings-body-password-body').find(':input').val();
		
		//Check to make sure the current password is valid
		if ( !t.checkPassword( em, currpass) ) {
			t.clearPasswordFields();
			return;
		}
		
		/* Check the new passwords for equality */
		var newpass1 = $('.account-settings-body-changepass-body').find(':input').val();
		var newpass2 = $('.account-settings-body-changepassconf-body').find(':input').val();
		if( newpass1 != newpass2){
			alert('New passwords do not match!');
			t.clearPasswordFields();
			return;
		}
		if( newpass1 == ""){	//Don't want to encode an empty string
			encodedPass = "";
		} else {
			encodedPass = hex_md5(newpass1);
		}
			//encode the parameters	
		var para = {"email" : em, "password" : encodedPass, "firstName" : first, "lastName" : last};
		//var para = {"email" : em, "password" : "", "firstName" : first, "lastName" : last};

		var para_encoded = JSON.stringify(para);
		url += para_encoded;

		//ajax call to get result
		$.ajax({
		  url: url,
		  success: function( result ) {
		   		var msg = jQuery.parseJSON(result);
		   		t.clearPasswordFields();
		   		var success = msg.success;
				
				//Print out the results of the ajax call
		   		alert(msg.message);
		  },
		  error: function(){
		  		alert('oops, we got an error!');
		  		t.clearPasswordFields();
		  }
	  
		});
	},	
	
	/* End all AJAX functions */


	handleHideChanges : function(el) {
		if ($(el).html() == 'Change Password -') {
			$(el).html('Change Password +');
			$('.account-settings-body-changepass').hide('fast');
			$('.account-settings-body-changepassconf').hide('fast');
		}
		else if ($(el).html() == 'Change Password +') {
			$(el).html('Change Password -');
			$('.account-settings-body-changepass').show('fast');
			$('.account-settings-body-changepassconf').show('fast');
		}
	},
	
	/*handleLogout : function() {
		var url = 'lib/userApi.php?__m=logout&__d=';
		
		var para = {};
			
		//encode the parameters
		var para_encoded = JSON.stringify(para);
			
		url += para_encoded;
	
		var $this = this;
		//ajax call to get result
		$.ajax({
		  url: url,
		  async:false,
		  success: function( result ) {
		  		//No return values from logout
		   		var msg = jQuery.parseJSON(result);
		   		window.location = '/login.html';
		  },
		  error: function(){
		  		alert('oops, we got an error!');
		  }
		});
	},*/
	
	
	addAllListeners : function () {
		var t = this;
		
		//Listener for the hiding the change password boxes
		$(".account-settings-change-password-toggle").click(function() {
			t.handleHideChanges(this);
		});
		
		//Listener on submit changes button for submitting changes to the DB
		$(".submit-account-changes-link").click(function() {
			t.submitUserAccountChanges();
		});
		
	}


}
